package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.cheer.ba.widget.observable.ObservableListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 通用搜索
 */
public class SearchAty extends BaseCommAty implements AdapterView.OnItemClickListener {

    //搜索关键字
    private EditText mEditKey;
    private String mSaveKey;

    @BindView(R.id.id_oil_card_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_search_listv)
    ObservableListView mObserListv;
    CommonAdapter<OilCardInfoModel> mAdapter;
    List<OilCardInfoModel> mOilCards = new ArrayList<OilCardInfoModel>();

    //确定按钮
    @BindView(R.id.id_search_sure_btn)
    Button mBtnSure;

    private boolean isBack;

    //记录点击的model
    private OilCardInfoModel mSaveCheckModel;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_search, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return !mOilCards.isEmpty();
    }

    @Override
    public void initView() {
        isBack = getIntent().getBooleanExtra(IntentKey.General.KEY_PAGE, false);
        if (isBack) {
            mBtnSure.setVisibility(View.VISIBLE);
        } else {
            mBtnSure.setVisibility(View.GONE);
        }
        mEditKey = setSearchTxt("", null);
        setTitleRight("搜索", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSaveKey = mEditKey.getText().toString().trim();
                if (StringUtils.isEmpty(mSaveKey)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请输入关键字");
                } else {
                    //搜索
                    if (hasDataInPage()) {
                        mXRefreshView.startRefresh();
                    } else {
                        loadData(true);
                    }
                }
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        setXRefreshView(mXRefreshView, true, false, false, false, new CheerHeadView(aty), null);
        mAdapter = new CommonAdapter<OilCardInfoModel>(aty, mOilCards, R.layout.adp_my_oilcard) {
            @Override
            public void convert(final ViewHolder helper, final OilCardInfoModel item) {
                if (null == item) {
                    return;
                }
                final CheckBox mCheckBox = (CheckBox) helper.getViewById(R.id.id_check_box);
                if (isBack) {
                    mCheckBox.setVisibility(View.VISIBLE);
                    if (checkMap.get(helper.getPosition(), false)) {
                        mCheckBox.setChecked(true);
                    } else {
                        mCheckBox.setChecked(false);
                    }
                    mCheckBox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mCheckBox.isChecked()) {
                                mSaveCheckModel = item;
                                mAdapter.setCheckAtPosFalse(helper.getPosition(), true);
                            } else {
                                mSaveCheckModel = null;
                                mAdapter.setCheckAtPosFalse(helper.getPosition(), false);
                            }
                        }
                    });
                } else {
                    mCheckBox.setVisibility(View.GONE);
                }
                helper.setText(R.id.id_oil_card_num_txt, StringUtils.replaceBankString(item.getCardNum(), 0));
                helper.setText(R.id.id_oil_card_txt, "加油啦车队卡");
                if (item.getCardType() == 1) {
                    helper.setText(R.id.id_oil_name_txt, "中国石油（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_china_oil_logo);
                } else if (item.getCardType() == 2) {
                    helper.setText(R.id.id_oil_name_txt, "中国石化（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_shihua_logo);
                } else {
                    helper.setText(R.id.id_oil_name_txt, "中国海油（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_haiyou_logo);
                }
                TextView mTxtCardActivity = (TextView) helper.getViewById(R.id.id_activity_txt);
                if (item.getCardStatus() == 1) {
                    //未激活
                    mTxtCardActivity.setVisibility(View.VISIBLE);
                } else {
                    mTxtCardActivity.setVisibility(View.GONE);
                }
            }
        };
        mObserListv.setAdapter(mAdapter);
        mObserListv.setOnItemClickListener(this);
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false);
            }
        });
    }

    /**
     * 加载数据
     */
    public void loadData(boolean isShLowoad) {
        ((OilMealPresenter) presenter).getMyOilCards(isShLowoad, "0", "", "", "", "", mSaveKey);
        stopRefresh(mXRefreshView, 2000);
    }

    @OnClick({R.id.id_search_sure_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //确定
            case R.id.id_search_sure_btn:
                if (null == mSaveCheckModel) {
                    SVProgressHUD.showInfoWithStatus(aty, "请选择油卡");
                } else {
                    BaseEvent event = new BaseEvent();
                    event.type = IntentKey.Oil.KEY_OIL_MODEL;
                    event.flag = true;
                    event.model = mSaveCheckModel;
                    EventBus.getDefault().post(event);
                    finish();
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        mXRefreshView.stopRefresh();
        if (null != t) {
            if (TextUtils.equals(ConstantTag.MY_OIL_CARDS, tag)) {
                mXRefreshView.setVisibility(View.VISIBLE);
                List<OilCardInfoModel> oilCards = (List<OilCardInfoModel>) t;

                mOilCards.clear();
                mOilCards.addAll(oilCards);
                mAdapter.notifyDataSetChanged();
            } else if (TextUtils.equals(ConstantTag.DATA_SUCCESS_NULL, tag)) {
                //没有油卡了
                mXRefreshView.setVisibility(View.GONE);
                mOilCards.clear();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        OilCardInfoModel model = (OilCardInfoModel) mAdapter.getItem(position - 1);
        Intent intent = new Intent(aty, OilCardDetailAty.class);
        intent.putExtra(IntentKey.General.KEY_MODEL, model);
        showActivity(aty, intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.Oil.DEL_OIL_CARD)) {
            //移除油卡
            loadData(true);
        } else if (TextUtils.equals(type, IntentKey.Oil.OIL_ACTIVITY_SUCCESS)) {
            //激活油卡成功
            loadData(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
